package com.ruoyi.web.controller.wnjk.app.shop;

import com.alipay.api.domain.ShopItem;
import com.alipay.api.internal.util.AlipaySignature;
import com.ruoyi.system.pay.domain.dto.PayRequestDTO;
import com.ruoyi.system.pay.domain.po.OrderQuery;
import com.ruoyi.system.pay.service.IPayService;
import com.ruoyi.system.wnjk.contents.Contents;
import com.ruoyi.system.wnjk.domain.po.PhysicalOrder;
import com.ruoyi.system.wnjk.domain.po.ShopOrder;
import com.ruoyi.system.wnjk.domain.po.ShopOrderDetail;
import com.ruoyi.system.wnjk.domain.vo.ShopOrderVo;
import com.ruoyi.system.wnjk.mapper.ShopOrderMapper;
import com.ruoyi.system.wnjk.producer.DirectProducer;
import com.ruoyi.system.wnjk.service.IShopItemService;
import com.ruoyi.system.wnjk.service.IShopOrderDetailService;
import com.ruoyi.system.wnjk.service.IShopOrderService;
import com.ruoyi.system.wnjk.service.impl.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/app/api")
public class ShopPayController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IPayService payService; // 支付服务

    @Autowired
    private IShopOrderService shopOrderService; // 订单服务

    @Autowired
    private IShopItemService shopItemService;   //商品服务

    @Autowired
    private IShopOrderDetailService shopOrderDetailService; // 订单详情服务

    @Autowired
    private DirectProducer directProducer;

    private String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjWMaj7mTWWYjiYKk4RyypIQVds80DesdC+bsOWOCk2uZi7w+izONFliO1gxnLL5mEobDldwiHZwZFq5gUJrwBcfMF2wuq8V15HyrKrv/p58M5NTo40MIZKtFAz6acVKi8LXbLPmgcTajQV8uAEsFupXn67msHEe+hKbDaxufBz1QcIxSpwyNOPsnRxs8Ex2JpyISayDfbxRPw5C1AqWltZSYbASY49khG2np3w5ToE4g3SwRFyem8Zodg0m0uGVKhDY+A7OqwIv+8cYgXoetvB8I90iU4AcVbb4O1eg/5gMR/j+C0l4gCBytpVGBIt/QDV5Xa/Jl9ZVOJYnO6Rzv/QIDAQAB"; // 支付宝公钥

    /**
     * 创建商品订单并发起支付
     *
     * @return 支付表单（HTML），用于跳转到支付宝支付页面
     */
    @PostMapping("/pay")
    public String createPayment(@RequestParam String orderId) {
        try {
            // 从Redis中获取订单信息
            ShopOrderVo orderRequest = (ShopOrderVo) redisTemplate.opsForValue().get(orderId);
            if (orderRequest == null) {
                throw new RuntimeException("订单不存在或已过期");
            } else {

                // 预扣库存
                List<ShopOrderDetail> orderDetails = orderRequest.getShopOrderDetailList();
                for (ShopOrderDetail detail : orderDetails) {
                    shopItemService.lockStock(detail.getItemId(), detail.getNum());
                }

                System.out.println("orderRequest = " + orderRequest);
                //构造返回的订单信息，添加到订单表中
                ShopOrder order = new ShopOrder();
                order.setId(Long.parseLong(orderId));
                order.setTotalFee(orderRequest.getTotalFee());   //总金额
                order.setPaymentType(orderRequest.getPaymentType());  //支付类型
                order.setUserId(orderRequest.getUserId());   //用户id
                order.setShopAddressId(orderRequest.getShopAddressId());  //用户地址
                order.setStatus(orderRequest.getStatus()); // 初始状态
                System.out.println(order);
                shopOrderService.insertShopOrder(order);
                //添加到订单详情表中
                List<ShopOrderDetail> detaillist = orderRequest.getShopOrderDetailList();//订单商品详情
                for (ShopOrderDetail shopOrderDetail : detaillist) {
                    shopOrderDetail.setOrderId(Long.parseLong(orderId));
                    shopOrderDetailService.insertShopOrderDetail(shopOrderDetail);
                }
            }

            //准备支付请求参数
            PayRequestDTO payRequestDTO = new PayRequestDTO();
            payRequestDTO.setOrderNumber(orderId); // 订单号
            payRequestDTO.setSourceType(Contents.Pay.TYPE_GW_SHOP); // 来源类型
            payRequestDTO.setSourceId(orderId); // 订单 ID
            payRequestDTO.setAmount(String.valueOf(orderRequest.getTotalFee())); // 支付金额
            payRequestDTO.setSubject("购买商品"); // 支付标题
            payRequestDTO.setBody("<<<商品订单支付>>>"); // 支付描述

            // 调用统一支付方法生成支付链接
            String payForm = payService.unifiedPay(payRequestDTO);

            System.out.println("payForm:" + payForm);

            OrderQuery orderQuery = new OrderQuery();
            orderQuery.setOrderNumber(orderId);
            orderQuery.setSourceType(Contents.Pay.TYPE_GW_SHOP);
//            directProducer.sendRequest(orderQuery);
            // 返回支付表单给前端
            return payForm;

        } catch (Exception e) {
            System.err.println("支付接口异常: " + e.getMessage());
            throw new RuntimeException("找不到订单，创建订单失败: " + e.getMessage(), e);
        }
    }

    /**
     * 支付宝异步回调接口
     */
    @PostMapping("/pay/notify")
    public String handleAlipayNotify(HttpServletRequest request) {
        try {
            // 1. 验证是否为支付宝回调
            boolean isAlipayCallback = payService.verifyPayCallback(request);
            if (!isAlipayCallback) {
                System.out.println("【支付回调】非支付宝合法回调，验证失败");
                return "failure";
            }

            // 2. 解析回调参数
            Map<String, String> params = new HashMap<>();
            for (String name : request.getParameterMap().keySet()) {
                params.put(name, request.getParameter(name));
            }

            // 4. 验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayPublicKey, "UTF-8", "RSA2");
            if (!signVerified) {
                System.out.println("【支付回调】签名验证失败");
                return "failure";
            }

            // 3. 获取订单号和支付状态
            String outTradeNo = params.get("out_trade_no"); // 订单号
            String orderId = outTradeNo.substring(2);
            String tradeStatus = params.get("trade_status"); // 支付状态

            // 4. 处理支付成功的逻辑
            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                // 从数据库中获取订单信息
                ShopOrder shopOrder = shopOrderService.selectShopOrderById(Long.parseLong(orderId));
                if (shopOrder == null) {
                    return "订单不存在或已过期"; // 订单不存在或已过期
                } else {
                    // 更新订单状态为 "已支付"
                    shopOrder.setStatus(2);
                    // 更新数据库里的订单
                    shopOrderService.updateShopOrder(shopOrder);
                }
            } else if ("TRADE_CLOSED".equals(tradeStatus) || "TRADE_FAILED".equals(tradeStatus)) {
                // 支付失败或订单关闭，回滚库存
                ShopOrderVo orderRequest = (ShopOrderVo) redisTemplate.opsForValue().get(orderId);
                if (orderRequest != null) {
                    List<ShopOrderDetail> orderDetails = orderRequest.getShopOrderDetailList();
                    for (ShopOrderDetail detail : orderDetails) {
                        Long itemId = detail.getItemId(); // 商品ID
                        Long quantity = detail.getNum(); // 购买数量
                        // 调用商品服务，回滚库存
                        shopItemService.increaseStock(itemId, quantity);
                    }
                }
                // 从Redis中移除订单
                redisTemplate.delete(orderId);
            }
            // 5. 返回 success 告诉支付宝处理成功
            return "success";

        } catch (Exception e) {
            System.err.println("异步回调处理异常: " + e.getMessage());
            return "failure";
        }
    }

}
